import React, { Component } from 'react';
import { Switch } from 'antd';
import ReactJson from 'react-json-view';
import './JsonEditor.less';

export class JsonEditor extends Component {

  state = {
    isShowEditor: false,
    text: '',
    source: null,
    jsonError: ''
  }

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.textChange(this.props.text);
  }

  componentDidUpdate(prevProps, preState) {
    if (this.props.nodeKey !== prevProps.nodeKey) {
      this.textChange(this.props.text || '');
    }
  }

  updateJsonData = (stateData) => {
    const text = stateData && stateData.text;
    if (typeof text !== 'string') {
      return;
    }
    this.setState(stateData, () => {
      if (typeof this.props.updateNodeState === 'function') {
        this.props.updateNodeState(text);
      }
    });
  }

  textChange = (text) => {
    let source, jsonError;
    try {
      source = JSON.parse(text);
    } catch (e) {
      jsonError = e.message;
    }
    this.updateJsonData({ text, source, jsonError });
  }

  dataChange = ({ updated_src: source }) => {
    const text = JSON.stringify(source);
    this.updateJsonData({ text, source });
  }

  switchChange = (isShowEditor) => {
    this.setState({ isShowEditor });
  }

  render() {
    return (
      <div className='editor-content'>
        <textarea
          className="textarea-txt"
          placeholder="请输入"
          value={this.state.text}
          onChange={e => this.textChange(e.target.value)}
        />
        <Switch onChange={this.switchChange} checkedChildren="JSON编辑" unCheckedChildren="JSON编辑" size="small" />
        {this.state.isShowEditor && (
          this.state.source ?
            <div className="json-content">
              <ReactJson
                name={false}
                collapsed
                collapseStringsAfterLength={12}
                src={this.state.source}
                onEdit={this.dataChange}
                onAdd={this.dataChange}
                onDelete={this.dataChange}
                displayDataTypes={false}
              />
            </div> : <div className="error-txt">JSON Error: {this.state.jsonError}</div>
        )}
      </div>
    );
  }
}